<template>
  <!-- 服务管理 -->
  <div class="innerPageTable-box-OneTwo value-set-list-wrap innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        ref="searchForm"
        :model="searchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <Form-item prop="org" :label="'单位名称'" v-if="!loading && isAdmin">
          <Select v-model="searchForm.org" clearable @on-change="searchValueSet">
            <Option v-for="item in treeData" :value="item.orgCode" :key="item.orgCode">{{ item.orgName }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="subType" :label="'类型'">
          <Select v-model="searchForm.subType" clearable @on-change="searchValueSet">
            <Option v-for="item in subTypeList" :value="item" :key="item">{{ item }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="period" :label="'当前填报周期'">
          <Select v-model="searchForm.period" clearable @on-change="searchValueSet">
            <Option v-for="item in periodList" :value="item" :key="item">{{ item }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="status" :label="'状态'">
          <Select v-model="searchForm.status" :clearable="!onlyView" @on-change="searchValueSet">
            <Option v-for="item in reportList" :value="item.key" :key="item.key">{{ item.name }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="isPassed" :label="'是否通过'">
          <Select v-model="searchForm.isPassed" clearable @on-change="searchValueSet">
            <Option v-for="item in isPassedList" :value="item.key" :key="item.key">{{ item.name }}</Option>
          </Select>
        </Form-item>

        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" @click="searchValueSet()" />
          <RPButton optType="reset" @click="resetAndSearchValueSet()" />
        </Form-item>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="valueSetTable" :config="pageTableConfig" v-if="!loading">
      <div slot="table-bar">
        <RPButton v-if="showAdd && !onlyView" optType="create" type="info" @click="newForm" />
      </div>
    </InnerPageTable>
  </div>
</template>

<script>
import permission from '@/mixin/permission'
import { reportStatus, STATUS_TYPE_APPROVED, STATUS_TYPE_DRAFT, STATUS_TYPE_PENDING } from '@/views/formConst'
import { tableColumns, ownerColumns } from './columns'
import dataApi from '@/api/formData'
import formCenterApi from '@/api/formCenter'
import { STATUS_TYPE_PUBLISHED } from '@/views/formConst'
import { mapState } from 'vuex'
import writeForm from '@/views/formCenter/writeForm/applyForm/index.vue'
import selectForm from './selectForm.vue'
import passed from './passed.vue'
export default {
  name: 'declarationFormList',
  mixins: [permission],
  props: {
    row: {
      type: Object,
      default: () => {}
    },
    onlyView: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: true,
      isAdmin: false,
      treeData: [],
      userCode: sessionStorage.userCode,
      operateForms: [],
      formPermissions: {},
      forms: [],
      formType: '',
      subTypeList: [],
      reportList: [],
      periodList: [],
      operateIds: [],
      isPassedList: [
        { key: 1, name: '是' },
        { key: 0, name: '否' }
      ],
      searchForm: {
        org: '',
        subType: '',
        isPassed: '',
        period: '',
        status: ''
      },
      formIdList: [],
      pageTableConfig: {
        loadDataFn: this.getServiceList,
        pageSize: 20,
        autoFirst: false //默认 就是 false, 要配置在这里
      }
    }
  },
  computed: {
    ...mapState(['orgList']),
    showAdd() {
      return this.operateForms.length > 0
    }
  },
  watch: {
    orgList(newValue, oldValue) {
      this.dealTreeData(newValue)
    }
  },
  mounted() {
    if (this.hasPermission('FORM_CREATE')) {
      //制表员（智数部人员默认显示已审批的）
      this.isAdmin = true
    }
    if (this.row.data.permission.formCreator) {
      //表单创建人
      this.pageTableConfig.columns = ownerColumns.bind(this)()
    } else {
      this.pageTableConfig.columns = tableColumns.bind(this)()
    }

    if (this.orgList.length <= 0) {
      this.$store.dispatch('getOrgList')
    } else {
      this.dealTreeData(this.orgList)
    }
    if (this.onlyView) {
      // 查看默认展示审核
      this.reportList = reportStatus.filter(item => item.key !== STATUS_TYPE_DRAFT && item.key !== STATUS_TYPE_PENDING)
      this.searchForm.status = STATUS_TYPE_APPROVED
    } else {
      this.reportList = reportStatus.filter(item => item.key !== STATUS_TYPE_DRAFT)
    }
    this.init()
  },
  methods: {
    init() {
      //快速跳转
      formCenterApi.menuFindList({ menu: this.row.value }).then(res => {
        this.operateForms = res.data.data.filter(item => item.permission.operate)
        this.forms = res.data.data
        this.formPermissions = {}
        this.forms.forEach(element => {
          this.formPermissions[element.id] = element.permission
        })
        this.formIdList = this.forms.map(item => item.id)
        this.subTypeList = [...new Set(this.forms.filter(item => item.subType !== '').map(item => item.subType))]
        this.operateIds = Array.from(new Set(this.forms.map(item => item.createBy)))
        if (this.formIdList.length > 0) {
          this.formType = this.forms[0].type
          this.getPeriodList(this.formIdList)
          this.$nextTick(() => this.searchValueSet())
        }
      })
    },
    dealTreeData(orgData) {
      let data = JSON.parse(JSON.stringify(this.treeToFlat(orgData)))
      data.forEach(node => {
        node.checked = false
        node.title = node.orgName
      })
      data[0].children = []
      this.treeData = data
      this.loading = false
    },
    treeToFlat(tree, parentId = null) {
      let flat = []
      for (let node of tree) {
        let copy = { ...node, parentId }
        flat.push(copy)
        if (node.children && node.children.length > 0) {
          flat = flat.concat(this.treeToFlat(node.children, node.id))
        }
      }
      return flat
    },
    async getPeriodList(formIds) {
      const res = await formCenterApi.formReportHistoryPeriod(formIds)
      this.periodList = Array.from(new Set(res.data))
    },
    // 跳转到具体表单
    enterForm(data) {
      new this.$sidelipPage(
        writeForm,
        {
          props: {
            id: data.id
          }
        },
        data => {
          data && this.searchValueSet(true)
        }
      )
    },
    //新建填报
    newForm() {
      if (this.operateForms.length > 1) {
        new this.$pageModal(
          selectForm,
          {
            props: {
              forms: this.operateForms
            }
          },
          data => {
            if (data) {
              this.enterForm(data)
            }
          }
        )
      } else {
        this.enterForm(this.operateForms[0])
      }
    },
    //编辑
    editForm(row) {
      new this.$sidelipPage(
        writeForm,
        {
          props: {
            id: row.formId,
            recordId: row.id,
            isEdit: true,
            updateTime: row.updateTime
          }
        },
        data => {
          data && this.searchValueSet(true)
        }
      )
    },
    // 详情
    viewForm(row) {
      new this.$sidelipPage(
        writeForm,
        {
          props: {
            id: row.formId,
            recordId: row.id,
            isDetail: true,
            updateTime: row.updateTime
          }
        },
        data => {
          data && this.searchValueSet(true)
        }
      )
    },
    editPass(row, value) {
      new this.$pageModal(
        passed,
        {
          props: {
            row: row
          }
        },
        data => {
          data && this.searchValueSet(true)
        }
      )
    },
    getServiceList(tableObj) {
      let { responseProcess, param } = tableObj
      const conditions = []
      Object.keys(this.searchForm).forEach(key => {
        let value = this.searchForm[key]
        if ((value && typeof value !== 'object') || Object.is(value, 0)) {
          conditions.push({
            fieldId: key,
            operator: 'is',
            value: value
          })
        }
      })
      param.condition.filterInfo = { conjunction: 'and', conditions }
      param.condition.formType = this.formType
      param.condition.formIdList = this.formIdList
      dataApi
        .getDataPage({
          ...param,
          currentPage: param.commonPageDTO.currentPage
        })
        .then(res => {
          let { pageSize, total, pageNum, records, pages } = res.data.data
          records.forEach(row => {
            row.contact = row.contact || '--'
            row.phone = row.phone || '--'
            row.email = row.email || '--'
            row.period = row.period || '--'
            row.score = row.score || '--'
            row.phone = row.phone || '--'
          })
          responseProcess({
            pageNum: pageNum,
            pageSize: pageSize,
            pages: pages,
            records: records || [],
            total: total
          })
        })
    },
    searchValueSet(isCurrent) {
      if (!isCurrent) {
        this.$refs['valueSetTable'].currentPage = 1
      }
      this.$refs['valueSetTable'].load(this.searchForm)
    },
    resetAndSearchValueSet() {
      this.$refs['searchForm'].resetFields()
      this.searchValueSet()
    }
  }
}
</script>
